import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NavController, NavParams, ToastController, Nav } from 'ionic-angular';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { PersonPage } from '../person/person';
import { Base64 } from 'js-base64';

import * as _ from 'lodash';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  group: FormGroup;
  showPassword = false;

  constructor(public navCtrl: NavController,
              public nav: Nav,
              public navParams: NavParams,
              public translate: TranslateService,
              private toastCtrl: ToastController,
              private builder: FormBuilder,
              private restService: RestService) {
    this.group = this.builder.group({
      username: [ '', [ Validators.required ] ],
      password: [ '', [ Validators.required ] ]
    });
  }

  login() {
    const username = this.group.controls.username.value;
    const password = this.group.controls.password.value;

    this.restService.clearup();
    this.restService.getTokenFromServer({
      grant_type: 'password',
      username: username,
      password: password,
      client_id: 'webmobile',
    }, (data) => {
      const token = data['access_token'];
      const refreshToken = data['refresh_token'];
      const userInfo = JSON.parse(Base64.decode(token.split('.')[1]));
      const user = {
        username: username,
        password: password,
        locale: userInfo.locale,
        instName: userInfo.given_name.replace('###INST###', ''),
        role: ''
      };

      switch (userInfo.locale) {
      case 'en':
        this.translate.use('en');
        break;
      case 'zh-CN':
        this.translate.use('zh');
        break;
      case 'zh-TW':
        this.translate.use('tw');
        break;
      }

      const roles = userInfo.realm_access.roles;
      if (_.isEmpty(roles)) {
        console.error('user have not assigned any roles');
        this.showToast(this.translate.get('invalidUserRole')['value']);
        return;
      }

      const validRoles = this.restService.listValidRoles();
      roles.forEach(role => {
        if (validRoles.indexOf(role) !== -1) {
          user.role = role;
        }
      });

      if (!user.role || user.role === 'user' || user.role === 'super') {
        this.showToast(this.translate.get('invalidUserRole')['value']);
        return;
      }

      this.restService.saveToken(token);
      this.restService.saveRefreshToken(refreshToken);
      this.restService.getWithParams('/data/institution/search/instName', {
        instName: user.instName
      }).subscribe(resp => {
        user['instId'] = resp['_embedded']['institutions'][0]['id'];
        this.restService.saveUser(user);
        this.restService.startRefreshToken();
        this.nav.setRoot(PersonPage);
      }, message => {
        this.showToast(this.translate.get('invalidInstitution')['value']);
      });
    }, () => {
      this.restService.get('/api/keycloak/validate/' + username).subscribe(data => {
        if (data.status === 404) {
          this.showToast(this.translate.get('userNotFound')['value']);
        } else {
          this.showToast(this.translate.get('wrongPassword')['value']);
        }
      }, message => {
        this.showToast(this.translate.get('failedToken')['value']);
        console.error(JSON.stringify(message));
      });
    });
  }

  showToast(message) {
    const toast = this.toastCtrl.create({
      message: message,
      duration: 5000,
      position: 'bottom'
    });

    toast.present(toast);
  }

  ionViewDidLoad() {
    const user = this.restService.getUser();
    if (_.isEmpty(user)) {
      return;
    }

    if (user.username) {
      this.group.controls.username.setValue(user.username);
    }
  }
}
